package J20241026_HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王圆豪
 * Date: 2024-10-27
 * Time: 20:26
 */
public class HashBuck2<K, V> {
    static class Node<K, V>{
        K key;
        V val;
        Node<K, V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    private Node<K, V>[] array = (Node<K, V>[])new Node[10];
    private int usedSize;
    private static final double LOAD_FACTOR = 0.75;

    public void push(K key, V val){
        int index = key.hashCode() % array.length;
        Node<K, V> cur = array[index];
        while (cur != null){
            if (cur.key.equals(key)){
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        Node<K, V> n = new Node<>(key, val);
        n.next = array[index];
        array[index] = n;
        usedSize++;

        if (usedSize * 1.0 / array.length >=0.75){
            expansion();
        }
    }

    private void expansion() {
        Node<K, V>[] newArray = (Node<K, V>[])new Node[2 * array.length];
        for (Node<K, V> n:
             array) {
            while (n != null){
                int newIndex = n.key.hashCode() % newArray.length;
                Node<K, V> cur = n.next;
                n.next = newArray[newIndex];
                newArray[newIndex] = n;
                n = cur;
            }
        }
        array = newArray;
    }

    public V getVal(K k){
        int h = k.hashCode();
        Node<K, V> n = array[h % array.length];
        while (n != null){
            if (n.key.equals(k)){
                return n.val;
            }
            n = n.next;
        }
        return null;
    }
}
